<?php
/**
 * alltosun.com  StudentController.Class.php
 * ============================================================================
 * 版权所有 (C) 2015 齐齐哈尔大学计算机与控制工程学院，并保留所有权利。
 * ============================================================================
 * $Author: 范志俊 (fanfzj@163.com) $
 * $Date: 2015-10-22 上午12:24:54 $
 */
namespace Admin\Controller;

use Think\Controller;
use Think\Upload;

class StudentController extends AuthController
{

    public function index()
    {
        $Student=M( 'Student' );

        //搜索条件
        $search=I('search',array() );

        $name=$search[ 'name' ];
        $sex=$search[ 'sex' ];
        $nation=$search[ 'nation' ];
        $major_id=$search[ 'major_id' ];
        $class_id=$search[ 'class_id' ];

        if( $name&&isset( $name ) ){
            $filter[ 'name' ]=array( 'like' , "%{$name}%" );
        }

        if( $sex&&isset( $sex ) ){
            $filter[ 'sex' ]=array( 'like' , "%{$sex}%" );
        }

        if( $nation&&isset( $nation ) ){
            $filter[ 'nation' ]=array( 'like' , "%{$nation}%" );
        }

        if( $major_id&&isset( $major_id ) ){
            $filter[ 'major_id' ]=$major_id;
        }

        if( $class_id&&isset( $class_id ) ){
            $filter[ 'class_id' ]=$class_id;
        }
        //分页
        $total=$Student->where( $filter )->count();

        if( $total ){
            $perNum=25;
            $Page=new \Think\Page( $total , $perNum );

            $Page->setConfig( 'prev' , "上一页" );//上一页
            $Page->setConfig( 'next' , '下一页' );//下一页
            $Page->setConfig( 'first' , '首页' );//第一页
            $Page->setConfig( 'last' , "末页" );//最后一页
            $Page->setConfig( 'theme' , '%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%' );

            $show=$Page->show();

            $this->assign( 'total' , $total );
            $this->assign( 'page' , $show );

        }

        $student_list=$Student->where( $filter )->order( 'major_id asc,id asc' )->limit( $Page->firstRow.','.$Page->listRows )->select();
        $this->assign( 'search' , $search );
        $this->assign( 'student_list' , $student_list );
        $this->display( 'student_list' );
    }
    public function export()
    {
        $student_list=M("Student")->order( 'major_id asc,id asc' )->select();
        $this->student_export($student_list );
    }
    //导出树木

    protected function student_export( $student_list=array() )
    {
        //print_r($goods_list);exit;
        $data=array();
        foreach( $student_list as $k=>$student_info ){
            $data[ $k ][ 'name' ]=$student_info[ 'name' ];
            $data[ $k ][ 'sex' ]=$student_info[ 'sex' ];
            $data[ $k ][ 'nation' ]=$student_info[ 'nation' ];
            $data[ $k ][ 'birthday' ]=$student_info[ 'birthday' ];
            $data[ $k ][ 'major' ]=get_title( 'major' , $student_info[ 'major_id' ] );
            $data[ $k ][ 'class' ]=get_title( 'class' , $student_info[ 'class_id' ] );
            $data[ $k ][ 'into_time' ]=$student_info[ 'into_time' ];
            $data[ $k ][ 'gk_score' ]=$student_info[ 'gk_score' ];
            $data[ $k ][ 'number' ]=$student_info[ 'number' ];
        }

        //print_r($goods_list);
//        print_r($data);
//
        foreach( $data as $field=>$v ){

            if( $field=='name' ){
                $headArr[]='姓名';
            }

            if( $field=='sex' ){
                $headArr[]='性别';
            }
            if( $field=='birthday' ){
                $headArr[]='出生年月日';
            }

            if( $field=='number' ){
                $headArr[]='身份证号';
            }

            if( $field=='nation' ){
                $headArr[]='民族';
            }

            if( $field=='gk_score' ){
                $headArr[]='高考分数';
            }


            if( $field=='into_time' ){
                $headArr[]='入学日期';
            }

            if( $field=='class' ){
                $headArr[]='班级';
            }
            if( $field=='major' ){
                $headArr[]='专业';
            }
        }

        $filename="student_list";

        $this->getExcel( $filename , $headArr , $data );
    }

    //添加树木

    private function getExcel( $fileName , $headArr , $data )
    {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import( "Org.Util.PHPExcel" );
        import( "Org.Util.PHPExcel.Writer.Excel5" );
        import( "Org.Util.PHPExcel.IOFactory.php" );

        $date=date( "Y_m_d" , time() );
        $fileName.="_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel=new \PHPExcel();
        $objProps=$objPHPExcel->getProperties();

        //设置表头
        $key=ord( "A" );
        //print_r($headArr);exit;
        foreach( $headArr as $v ){
            $colum=chr( $key );
            $objPHPExcel->setActiveSheetIndex( 0 )->setCellValue( $colum.'1' , $v );
            $objPHPExcel->setActiveSheetIndex( 0 )->setCellValue( $colum.'1' , $v );
            $key+=1;
        }

        $column=2;
        $objActSheet=$objPHPExcel->getActiveSheet();

        //print_r($data);exit;
        foreach( $data as $key=>$rows ){ //行写入
            $span=ord( "A" );
            foreach( $rows as $keyName=>$value ){// 列写入
                $j=chr( $span );
                $objActSheet->setCellValue( $j.$column , $value );
                $span++;
            }
            $column++;
        }

        $fileName=iconv( "utf-8" , "gb2312" , $fileName );

        //重命名表
        //$objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex( 0 );
        ob_end_clean();//清除缓冲区,避免乱码
        header( 'Content-Type: application/vnd.ms-excel' );
        header( "Content-Disposition: attachment;filename=\"$fileName\"" );
        header( 'Cache-Control: max-age=0' );

        $objWriter=\PHPExcel_IOFactory::createWriter( $objPHPExcel , 'Excel5' );
        $objWriter->save( 'php://output' ); //文件通过浏览器下载
        exit;
    }


    //编辑类别

    public function add()
    {
        $this->display( 'student_add' );
    }

    //保存数据

    public function check_title()
    {
        $title=I( 'param' );
        $result=check_title( 'student' , $title );

        if( $result ){
            $this->ajaxReturn( array( 'status'=>'n' , 'info'=>'该学生已经存在' ) );
        } else{
            $this->ajaxReturn( array( 'status'=>'y' , 'info'=>'' ) );
        }

    }
    //修改界面
    public function edit()
    {
        $id=I( 'id' );
        $student_info=M( 'Student' )->find( $id );

        //print_r($goods_info);

        $this->assign( 'student_info' , $student_info );
        $this->display( 'student_add' );
    }

    //保存
    public function save()
    {
        $id=I( 'Id' );
        $Student=M( 'Student' );
        $info=$Student->find( $id );

        $data[ 'name' ]=I( 'name' , '' );
        $data[ 'sex' ]=I( 'sex' , '男' );
        $data[ 'nation' ]=I( 'nation' , '汉族' );
        $data[ 'birthday' ]=I( 'birthday' , '1990-1-1' );
        $data[ 'number' ]=I( 'number' , '' );
        $data[ 'gk_score' ]=I( 'gk_score' , '' );
        $data[ 'into_time' ]=I( 'first_fight' , '2014-9-1' );
        $data[ 'major_id' ]=I( 'major_id' , 1 );
        $data[ 'class_id' ]=I( 'class_id' , 1 );

        if( $info ){
            //print_r($data);echo '1111';exit;
            //更新操作
            $data[ 'create_time' ]=Date( 'Y-m-d H:i:s' );
            $result=$Student->where( array( 'Id'=>$id ) )->save( $data );
            if( $result||$result===0 ){
                $this->ajaxReturn( array( 'status'=>'ok' , 'info'=>'学生信息修改成功' ) );
            } else if( $result===FALSE ){
                $this->ajaxReturn( array( 'status'=>'error' , 'info'=>'学生信息修改失败' ) );
            }
        } else{
            //入库操作
            $data[ 'create_time' ]=date( 'Y-m-d H:i:s' , time() );

            //print_r($data);echo '2222';exit;

            $result=$Student->add( $data );
            if( $result ){
                $this->ajaxReturn( array( 'status'=>'ok' , 'info'=>'学生信息添加成功' ) );
            } else{
                $this->ajaxReturn( array( 'status'=>'error' , 'info'=>'学生信息添加失败' ) );
            }
        }

    }

    //导入数据页面

    public function del()
    {
        $id=I( 'id' );
        $result=M( 'Student' )->delete( $id );
        if( $result ){
            $this->success( '学生信息删除成功,正在转跳到学生列表' );
        } else if( $result ){
            $this->erroe( '学生信息删除失败' );
        }
    }

    //导入数据方法

    public function upload()
    {
        header( "Content-Type:text/html;charset=utf-8" );
        $upload=new \Think\Upload();// 实例化上传类
        $upload->maxSize=10485760;// 设置附件上传大小
        $upload->exts=array( 'xls' , 'xlsx' );// 设置附件上传类
        $upload->savePath='/xls/'; // 设置附件上传目录
        // 上传文件
        $info=$upload->uploadOne( $_FILES[ 'excelData' ] );
        $filename='./Uploads'.$info[ 'savepath' ].$info[ 'savename' ];
        $exts=$info[ 'ext' ];
        //print_r($info);exit;
        if( ! $info ){// 上传错误提示错误信息
            $this->error( $upload->getError() );
        } else{// 上传成功
            $this->student_import( $filename , $exts );
        }
    }

//保存导入数据

    protected function student_import( $filename , $exts='xls' )
    {
        $bool=false;
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能import导入
        import( "Org.Util.PHPExcel" );
        //创建PHPExcel对象，注意，不能少了\
        $PHPExcel=new \PHPExcel();
        //如果excel文件后缀名为.xls，导入这个类
        if( $exts=='xls' ){
            import( "Org.Util.PHPExcel.Reader.Excel5" );
            $PHPReader=new \PHPExcel_Reader_Excel5();
        } else if( $exts=='xlsx' ){
            import( "Org.Util.PHPExcel.Reader.Excel2007" );
            $PHPReader=new \PHPExcel_Reader_Excel2007();
        }


        //载入文件
        $PHPExcel=$PHPReader->load( $filename );
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$PHPExcel->getSheet( 0 );
        //获取总列数
        $allColumn=$currentSheet->getHighestColumn();
        //获取总行数
        $allRow=$currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for( $currentRow=1 ; $currentRow<=$allRow ; $currentRow++ ){
            //从哪列开始，A表示第一列
            for( $currentColumn='A' ; $currentColumn<=$allColumn ; $currentColumn++ ){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $cell=$currentSheet->getCell( $address )->getValue();
                //$cell = $data[$currentRow][$currentColumn];
                if( $cell instanceof PHPExcel_RichText ){
                    $cell=$cell->__toString();
                }
                //print_r($cell);
                $data[ $currentRow ][ $currentColumn ]=$cell;
                //$this->save_import($cell);
            }
            //var_dump($data);
            //$data[$currentRow-1]=$cell;

        }
        //var_dump($data);
        $this->save_import( $data );
    }


//导入数据方法

    public function save_import( $data )
    {
        //print_r($data);exit;

        $Student=M( 'Student' );
        $add_time=date( 'Y-m-d H:i:s' , time() );
        //var_dump($data);
        foreach( (array) $data as $k=>$v ){
            if( $k>=2 ){
                //姓名
                $name=$v[ 'A' ];
                $info[ $k-2 ][ 'name' ]=$name;
                //性别
                $sex=$v[ 'B' ];
                $info[ $k-2 ][ 'sex' ]=$sex;
                //名族
                $nation=$v[ 'C' ];
                $info[ $k-2 ][' nation']=$nation;
                //出生日期
                $birthday=$v[ 'D' ];
                $info[ $k-2 ][ 'birthday' ]=$birthday;
                //专业
                $major=$v[ 'E' ];
                if( empty( $major ) ){
                    $info[ $k-2 ][ 'major_id' ]=1;
                } else{
                    $major_id=M( 'Major' )->where( array( 'name'=>$major ) )->getField( 'Id' );
                    if( $major_id ){
                        $info[ $k-2 ][ 'major_id' ]=$major_id;
                    } else{
                        $new_major_id=M( 'Major' )->add( array( 'name'=>$major , 'add_time'=>$add_time ) );
                        $info[ $k-2 ][ 'major_id' ]=new_major_id;
                    }
                }
                //班级
                $class=$v[ 'F' ];
                if(empty($class) ){
                    $info[ $k-2 ][ 'class_id' ]=1;
                } else{
                    $class_id=M( 'Class' )->where( array( 'name'=>$class ) )->getField( 'id' );
                    $class_data['name']=$class;
                    $class_data['add_time']=$add_time;
                    $class_data['major_id']=$info[ $k-2 ][ 'major_id' ];
                    $class_data['Id']=$class_id;
                    if( $class_id ){
                        $info[ $k-2 ][ 'class_id' ]=$class_id;
                        M('Class')->save($class_data);
                    } else{
                        $new_class_id=M( 'Class' )->add($class_data);
                        $info[ $k-2 ][ 'class_id' ]=$new_class_id;
                    }
                }
                //入学日期
                $into_time=$v[ 'G' ];
                $info[ $k-2 ][ 'into_time' ]=$into_time;
                //高考分数
                $gk_score=$v[ 'H' ];
                $info[ $k-2 ][ 'gk_score' ]=$gk_score;
                //身份证号
                $number=$v[ 'I' ];
                $info[ $k-2 ][ 'number' ]=$number;

                $result=$Student->where( array( 'name'=>$name ) )->find();

//                print_r($v);
                if( $result ){
                    //更新操作
                    $result=$Student->where( array( 'name'=>$name ) )->save( $info[ $k-2 ] );
                } else{
                    //入库操作
                    $info[ $k-2 ][ 'create_time' ]=$add_time;
                    $result=$Student->add( $info[ $k-2 ] );
                    $login_info['std_id']=$result;
                    M("Login")->save($login_info)->add();
                }
            }
            unset($info);
            //echo $v['F'];
        }
        if( false!==$result||0!==$result ){
            $this->success( '学生导入成功' , __ROOT__.'/Admin/Student/index' );
        } else{
            $this->error( '学生导入失败' );
        }
    }

    //导出excel操作

    public function import()
    {
        $this->display( 'student_import' );
    }


//上传图片
    public function upload_img()
    {
        $id=I('std_id');
        $img=$_FILES[ 'img_upload' ];
        if(!empty( $img ) ){
            import( 'ORG.Util.UploadFile' );
            $upload=new Upload();
            $upload->maxSize=10485760;
            $upload->exts=array( 'jpg' , 'gif' , 'png' , 'jpeg' );
            $upload->rootPath='./Uploads/';
            $upload->savePath='Image/'.$id.'/';
            $upload->saveName=time().'_'.mt_rand();
            $info=$upload->upload();
            if($info ){
                $img_data[ 'std_id' ]=$id;
                $img_data[ 'url' ]=$upload->rootPath.$info[ 'img_upload' ][ 'savepath' ].$info[ 'img_upload' ][ 'savename' ];
                $result=M( 'Image' )->where(array("std_id"=>$id))->save($img_data );
                if($result||$result==0)
                {
                    $data=array(
                        "status"=>0,
                        "info"=>"头像设置成功"
                    );
                }
                else
                {
                    $data=array(
                        "status"=>1,
                        "info"=>"头像设置失败"
                    );
                }
            } else{
                $data=array(
                    "status"=>1,
                    "info"=>"图片信息有误"
                );
            }
        } else{
           $data=array(
               "status"=>1,
               "info"=>"图片文件不存在"
           );
        }
        $this->ajaxReturn( $data );
    }
}